import 'dart:async';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:meco/common/index.dart';

class FiringController extends GetxController {
  FiringController();

  // 仓库
  final CeramicRepository _ceramicRepository = CeramicRepository();
  final CeramicStageRepository _ceramicStageRepository =
      CeramicStageRepository();

  // 用户服务
  final UserService _userService = Get.find<UserService>();

  // 当前陶瓷作品
  final Rx<Ceramic?> currentCeramic = Rx<Ceramic?>(null);

  // 所有阶段列表
  final RxList<CeramicStage> stages = <CeramicStage>[].obs;

  // 当前活动阶段索引
  final RxInt currentStageIndex = 0.obs;

  // 计时器
  Timer? _timer;

  // 当前阶段已计时秒数
  final RxInt currentSeconds = 0.obs;

  // 页面状态
  final RxBool isLoading = true.obs;
  final RxBool hasError = false.obs;
  final RxString errorMessage = ''.obs;

  // 阶段名称
  final List<String> stageNames = [
    'Raw material preparation',
    'Wheel throwing',
    'Dry and leave to crack',
    'Repair and decoration',
    'Glaze firing',
    'Finished product processing',
  ];

  // 阶段图标
  final List<IconData> stageIcons = [
    Icons.touch_app,
    Icons.air,
    Icons.local_fire_department,
    Icons.brush,
    Icons.wb_sunny,
    Icons.local_fire_department,
  ];

  @override
  void onInit() {
    super.onInit();
    _loadData();
  }

  // 公共方法用于视图重试调用
  Future<void> initData() async {
    await _loadData();
  }

  // 初始化数据
  Future<void> _loadData() async {
    isLoading.value = true;
    hasError.value = false;

    try {
      // 检查用户是否登录
      if (!_userService.isLoggedIn.value) {
        await _userService.checkLoginThenExecute(
          onLoggedIn: () {},
          loginRequiredMessage: 'You need to login to use the firing timer',
        );

        if (!_userService.isLoggedIn.value) {
          Get.back();
          return;
        }
      }

      // 查找是否有正在进行中的阶段或用户现有的陶瓷作品
      await _findRunningStage();

      // 如果没有找到现有陶瓷作品，创建新的
      if (currentCeramic.value == null) {
        await _createNewCeramic();
      }
    } catch (e) {
      hasError.value = true;
      errorMessage.value = 'Initialization failed: $e';
      print('Firing page initialization failed: $e');
    } finally {
      isLoading.value = false;
      update(["firing"]);
    }
  }

  // 处理阶段行为（开始、完成或切换）
  Future<void> handleStageAction(int index) async {
    // 检查阶段顺序
    if (index > 0 && index > currentStageIndex.value) {
      // 检查前一个阶段是否已完成
      final previousStage = stages[index - 1];
      if (previousStage.status != CeramicStageStatus.completed) {
        EasyLoading.showInfo('Please complete the previous stage first');
        return;
      }
    }

    // 切换到选定阶段
    if (canSwitchToStage(index)) {
      // 如果是切换阶段，先执行切换
      currentStageIndex.value = index;
      update(["firing"]);

      // 获取当前阶段
      final currentStage = stages[index];

      // 根据状态执行相应操作
      if (currentStage.status == CeramicStageStatus.pending) {
        await startCurrentStage();
      } else if (currentStage.status == CeramicStageStatus.running) {
        await completeCurrentStage();
      }
    } else {
      EasyLoading.showInfo('Cannot access this stage yet');
    }
  }

  // 判断是否可以切换到指定阶段
  bool canSwitchToStage(int index) {
    if (index < 0 || index >= stages.length) return false;

    // 已完成的阶段或当前阶段可以访问
    if (index <= currentStageIndex.value) return true;

    // 可以切换到已完成阶段的下一个阶段
    if (index == currentStageIndex.value + 1 &&
        stages[currentStageIndex.value].status ==
            CeramicStageStatus.completed) {
      return true;
    }

    return false;
  }

  // 查找用户的陶瓷作品和进行中的阶段
  Future<void> _findRunningStage() async {
    // 当前用户ID
    final userId = _userService.currentUser.value!.id!;

    // 获取用户的所有陶瓷作品和阶段
    final ceramics = await _ceramicStageRepository.getUserCeramics(userId);

    if (ceramics.isEmpty) {
      // 用户没有陶瓷作品，返回空
      return;
    }

    // 按陶瓷作品分组存储阶段信息
    Map<int, List<Map<String, dynamic>>> ceramicStagesMap = {};

    // 首先处理所有数据，按陶瓷ID分组
    for (var item in ceramics) {
      final ceramicId = item['ceramic_id'];

      // 跳过已标记为完成的陶瓷作品
      if (item['is_completed'] == 1) {
        continue;
      }

      if (!ceramicStagesMap.containsKey(ceramicId)) {
        ceramicStagesMap[ceramicId] = [];
      }
      ceramicStagesMap[ceramicId]!.add(item);
    }

    // 如果过滤后没有未完成的陶瓷作品，直接返回
    if (ceramicStagesMap.isEmpty) {
      return;
    }

    // 查找有正在进行阶段的陶瓷作品
    for (var ceramicId in ceramicStagesMap.keys) {
      final stagesData = ceramicStagesMap[ceramicId]!;
      bool hasRunningStage = false;

      // 检查该陶瓷是否有正在进行的阶段
      for (var stageData in stagesData) {
        if (stageData['status'] == CeramicStageStatus.running.index) {
          hasRunningStage = true;
          break;
        }
      }

      if (hasRunningStage) {
        // 创建陶瓷模型
        final firstItem = stagesData.first;
        final ceramic = Ceramic.fromJson({
          'id': firstItem['ceramic_id'],
          'user_id': firstItem['user_id'],
          'title': firstItem['title'],
          'description': firstItem['description'],
          'image_url': firstItem['image_url'],
          'is_skipped': firstItem['is_skipped'] == 1,
          'is_completed': firstItem['is_completed'] == 1,
          'like_count': firstItem['like_count'] ?? 0,
          'favorite_count': firstItem['favorite_count'] ?? 0,
          'created_at': firstItem['c_created_at'],
          'updated_at': firstItem['c_updated_at'],
        });

        currentCeramic.value = ceramic;

        // 获取该陶瓷的所有阶段
        stages.value = await _ceramicStageRepository.getStagesByCeramicId(
          ceramic.id!,
        );

        // 找出当前活动阶段
        for (int i = 0; i < stages.length; i++) {
          if (stages[i].status == CeramicStageStatus.running) {
            currentStageIndex.value = i;

            // 计算已经运行的时间
            if (stages[i].startTime != null) {
              currentSeconds.value =
                  DateTime.now().difference(stages[i].startTime!).inSeconds;
              _startTimer();
            }

            break;
          }
        }

        return; // 找到进行中的阶段就返回
      }
    }

    // 如果没有正在进行的阶段，使用最近的未完成陶瓷作品
    if (ceramicStagesMap.isNotEmpty) {
      // 第一个陶瓷作品（按创建时间倒序）
      final latestCeramicId = ceramicStagesMap.keys.first;
      final latestCeramicData = ceramicStagesMap[latestCeramicId]!;

      // 创建陶瓷模型
      final firstItem = latestCeramicData.first;
      final ceramic = Ceramic.fromJson({
        'id': firstItem['ceramic_id'],
        'user_id': firstItem['user_id'],
        'title': firstItem['title'],
        'description': firstItem['description'],
        'image_url': firstItem['image_url'],
        'is_skipped': firstItem['is_skipped'] == 1,
        'is_completed': firstItem['is_completed'] == 1,
        'like_count': firstItem['like_count'] ?? 0,
        'favorite_count': firstItem['favorite_count'] ?? 0,
        'created_at': firstItem['c_created_at'],
        'updated_at': firstItem['c_updated_at'],
      });

      currentCeramic.value = ceramic;

      // 获取该陶瓷的所有阶段
      stages.value = await _ceramicStageRepository.getStagesByCeramicId(
        ceramic.id!,
      );

      // 找出最新状态的阶段索引
      int latestStageIndex = 0;
      bool foundCompleted = false;

      // 按阶段类型顺序寻找最后一个已完成的阶段
      for (int i = 0; i < stages.length; i++) {
        if (stages[i].status == CeramicStageStatus.completed) {
          latestStageIndex = i + 1 >= stages.length ? i : i + 1;
          foundCompleted = true;
        }
      }

      // 如果都没完成，就显示第一个阶段
      if (!foundCompleted) {
        latestStageIndex = 0;
      }

      currentStageIndex.value = latestStageIndex;
    }
  }

  // 创建新的陶瓷作品和阶段
  Future<void> _createNewCeramic() async {
    final now = DateTime.now();

    // 创建新的陶瓷作品
    final ceramic = Ceramic(
      userId: _userService.currentUser.value!.id!,
      createdAt: now,
      updatedAt: now,
    );

    // 保存到数据库
    final ceramicId = await _ceramicRepository.addCeramic(ceramic);

    // 更新当前陶瓷作品
    currentCeramic.value = ceramic.copyWith(id: ceramicId);

    // 创建所有阶段
    stages.value = await _ceramicStageRepository.createStagesForCeramic(
      ceramicId,
    );

    // 默认第一个阶段
    currentStageIndex.value = 0;
  }

  // 开始当前阶段
  Future<void> startCurrentStage() async {
    if (stages.isEmpty || currentStageIndex.value >= stages.length) return;

    // 获取当前阶段
    final currentStage = stages[currentStageIndex.value];

    // 如果阶段已经在运行，不做操作
    if (currentStage.status == CeramicStageStatus.running) return;

    // 开始阶段
    final updatedStage = await _ceramicStageRepository.startStage(
      currentStage.id!,
    );
    if (updatedStage != null) {
      // 更新阶段数据
      stages[currentStageIndex.value] = updatedStage;

      // 重置计时器
      currentSeconds.value = 0;
      _startTimer();

      // 显示开始信息
      EasyLoading.showSuccess('Stage started');

      update(["firing"]);
    }
  }

  // 完成当前阶段
  Future<void> completeCurrentStage() async {
    if (stages.isEmpty || currentStageIndex.value >= stages.length) return;

    // 获取当前阶段
    final currentStage = stages[currentStageIndex.value];

    // 如果阶段不在运行状态，不做操作
    if (currentStage.status != CeramicStageStatus.running) return;

    // 停止计时器
    _stopTimer();

    // 完成阶段
    final updatedStage = await _ceramicStageRepository.completeStage(
      currentStage.id!,
    );
    if (updatedStage != null) {
      // 更新阶段数据
      stages[currentStageIndex.value] = updatedStage;

      // 如果不是最后一个阶段，切换到下一个阶段
      if (currentStageIndex.value < stages.length - 1) {
        EasyLoading.showSuccess('Stage completed');
        currentStageIndex.value++;
      } else {
        EasyLoading.showSuccess('All stages completed!');
      }

      update(["firing"]);
    }
  }

  // 切换到特定阶段
  void switchToStage(int index) {
    if (canSwitchToStage(index)) {
      currentStageIndex.value = index;
      update(["firing"]);
    } else {
      EasyLoading.showInfo('Cannot access this stage yet');
    }
  }

  // 启动计时器
  void _startTimer() {
    _stopTimer();
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      currentSeconds.value++;
      update(["timer"]);
    });
  }

  // 停止计时器
  void _stopTimer() {
    _timer?.cancel();
    _timer = null;
  }

  // 格式化时间
  String formatTime(int seconds) {
    final hours = seconds ~/ 3600;
    final minutes = (seconds % 3600) ~/ 60;
    final secs = seconds % 60;

    return '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${secs.toString().padLeft(2, '0')}';
  }

  // 上传并分享
  Future<void> uploadAndShare() async {
    try {
      // 检查是否所有阶段都已完成
      bool allCompleted = true;
      for (var stage in stages) {
        if (stage.status != CeramicStageStatus.completed) {
          allCompleted = false;
          break;
        }
      }

      if (!allCompleted) {
        EasyLoading.showInfo(
          'Please complete all firing steps before uploading',
        );
        return;
      }

      // 跳转到上传页面，传递陶瓷作品ID和跳过标志
      Get.toNamed(
        Routes.upload,
        arguments: {
          'ceramic_id': currentCeramic.value!.id,
          'is_skipped': false,
        },
      );
    } catch (e) {
      EasyLoading.showError('Failed to upload: $e');
    }
  }

  @override
  void onClose() {
    _stopTimer();
    super.onClose();
  }
}
